﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
using Newtonsoft.Json;
using System.Windows.Interop;
using System.Threading;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Diagnostics;
using System.Xml;

namespace desktop
{
    public partial class Home : DesktopForm
    {
        public static XmlDocument doc = new XmlDocument();
        static string StartupPath = Application.StartupPath;
        /// <summary>
        /// 配置文件
        /// </summary>
        public static string configPath = StartupPath + "\\desktop.config.xml";
        /// <summary>
        /// 图标信息
        /// </summary>
        private List<Models.Icon> icon = null;
        /// <summary>
        /// 应用信息
        /// </summary>
        private List<Models.DesktopInfo> desktopInfo = null;
        /// <summary>
        /// 执行文件信息
        /// </summary>
        private Models.FolderInfo _exeFolder = null;

        public Home()
        {
            InitializeComponent();
            icon = new List<Models.Icon>();
            _exeFolder = new Models.FolderInfo()
            {
                icon = "",
                name = "exe",
                path = StartupPath + "\\NewFolder\\exe",
                files = new List<Models.FileInfo>(),
                folders = new List<Models.FolderInfo>()
            };
            desktopInfo = new List<Models.DesktopInfo>();
            //SetClassLong(this.Handle, GCL_STYLE, GetClassLong(this.Handle, GCL_STYLE) | CS_DropSHADOW);
            //隐藏任务栏区图标
            this.ShowInTaskbar = false;
            //图标显示在托盘区
            this.notifyIcon1.Icon = new Icon(ReadResource("desktop.favicon-20210827091821284.ico"));

            //this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);

        }

        private void Home_Load(object sender, EventArgs e)
        {
            webBrowser1.ObjectForScripting = this;
            SetWindowRegion();

            ReadXml();
            LoadConfigToModels();
        }

        #region 配置文件操作


        /// <summary>
        /// 加载配置文件到内存
        /// </summary>
        private void ReadXml()
        {
            desktopInfo = new List<Models.DesktopInfo>();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;//忽略文档里面的注释
            XmlReader reader = XmlReader.Create(configPath, settings);
            doc.Load(reader);
            reader.Close();
        }

        /// <summary>
        /// 读取配置信息到实体类
        /// </summary>
        private void LoadConfigToModels()
        {
            // 根节点
            XmlNode xn = doc.SelectSingleNode("Desktop");

            // Application 信息读取
            XmlNode xnl = xn.SelectSingleNode("Application");
            var xnl1 = (XmlElement)xnl.SelectSingleNode("WindowsTopMost");
            var xnl2 = (XmlElement)xnl.SelectSingleNode("WindowsLocation");
            //var xnl3 = (XmlElement)xnl.SelectSingleNode("DropType"); 
            this.TopMost = bool.Parse(xnl1.GetAttribute("value"));
            this.Location = new Point(int.Parse(xnl2.GetAttribute("left")), int.Parse(xnl2.GetAttribute("right")));

            // DesktopInfo 信息读取
            var outerFile = xn.SelectSingleNode("DesktopInfo").ChildNodes;
            foreach (XmlElement element in outerFile)
            {
                //var element = (XmlElement)item;
                var number = element.GetAttribute("number");
                var nowPath = element.GetAttribute("nowPath");
                var originalPath = element.GetAttribute("originalPath");
                var type = element.GetAttribute("type");
                desktopInfo.Add(new Models.DesktopInfo()
                {
                    originalPath = originalPath,
                    nowPath = nowPath,
                    type = type,
                    number = number
                });
            }
        }

        /// <summary>
        /// 修改元素属性
        /// </summary>
        /// <param name="element"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        private void WriteXml(XmlElement element, string name, string value)
        {
            element.SetAttribute(name, value);
            doc.Save(configPath);
        }

        /// <summary>
        /// 修改元素属性-可修改单个元素的多个属性
        /// </summary>
        /// <param name="element"></param>
        /// <param name="keyValue"></param>
        private void WriteXml(XmlElement element, List<Models.Key_Value> keyValue)
        {
            foreach (var item in keyValue)
            {
                element.SetAttribute(item.key, item.value);
            }
            doc.Save(configPath);
        }
        #endregion

        /// <summary>
        /// 窗体大小改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Home_Resize(object sender, EventArgs e)
        {
            SetWindowRegion();
        }

        #region JS调用C#
        /// <summary>
        /// html加载完成事件
        /// </summary>
        public string Html_Load()
        {
            Loading();
            string windowsInfo = JsonConvert.SerializeObject(new Models.WindowsInfo()
            {
                topMost = this.TopMost
            });
            return windowsInfo;
        }
        /// <summary>
        /// JS方法--用于C#调用的方法
        /// </summary>
        List<string> JsFunction = new List<string>();
        public void MaxWindows()
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }
        public void HideWindows()
        {
            //this.WindowState = FormWindowState.Minimized;
            this.Hide();
        }
        //无窗体拖拽
        [DllImport("user32.dll")]//拖动无窗体的控件
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        public int mousedown()
        {
            //拖动窗体
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
            int windows_show = Mouseup();
            var element = (XmlElement)doc.SelectSingleNode("Desktop").SelectSingleNode("Application").SelectSingleNode("WindowsLocation");
            var newElement = new List<Models.Key_Value>();
            newElement.Add(new Models.Key_Value()
            {
                key = "left",
                value = (this.Location.X > 0) ? this.Location.X.ToString() : "0"
            });
            newElement.Add(new Models.Key_Value()
            {
                key = "right",
                value = (this.Location.Y > 0) ? this.Location.Y.ToString() : "0"
            });
            WriteXml(element, newElement);
            return windows_show;
        }

        public void AddApp(int type)
        {
            if (type == 0)
            {
                ShowDragIn();
            }
            else
            {
                //加一个空收藏夹
            }
        }

        public void OpenExe(string name)
        {
            if (name != null)
            {
                OpenFile(name);
            }
        }
        public void OpenFolder(string filePath)
        {
            if (filePath != null)
            {
                filePath = filePath.Replace("/", "\\");
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
                psi.Arguments = "/e,/select," + filePath;
                System.Diagnostics.Process.Start(psi);
            }
        }

        public void FormResize(int width, int height)
        {
            if (width == 0 && height == 0) return;
            this.Width = width;
            this.Height = height;

            Console.WriteLine(width + ":" + height);
        }

        public void DragoutWindows()
        {
            InAnimation(arrows: 8);
        }
        /// <summary>
        /// 重新加载
        /// </summary>
        public void Rerun()
        {
            ReadXml();//重新装载Xml
            LoadConfigToModels();//设置 - 配置文件
            Html_Load();//加载Html
        }
        public bool Ding()
        {
            this.TopMost = !this.TopMost;
            var element = (XmlElement)doc.SelectSingleNode("Desktop").SelectSingleNode("Application").SelectSingleNode("WindowsTopMost");
            WriteXml(element, "value", this.TopMost.ToString());
            return this.TopMost;
        }
        /// <summary>
        /// 设置文件排序Xml   --bug
        /// </summary>
        /// <param name="path">文件当前路径</param>
        /// <param name="number">排序 +∞</param>
        public void AppLocation(string path, string oldNumber, string newNumber)
        {
            int _oldNumber = int.Parse(oldNumber), _newNumber = int.Parse(newNumber), index = _newNumber;
            bool forward = (_oldNumber > _newNumber) ? true : false;
            var element = doc.SelectSingleNode("Desktop").SelectSingleNode("DesktopInfo").ChildNodes;
            foreach (XmlElement item in element)
            {
                string xmlPath = item.GetAttribute("nowPath").Replace("\\", "/");
                int xmlNumber = int.Parse(item.GetAttribute("number"));
                if (forward)
                {
                    //新位置开始改 --> 原位置  
                    if (xmlNumber >= _newNumber && xmlNumber < _oldNumber)
                    {
                        //index++;
                        item.SetAttribute("number", (xmlNumber + 1).ToString());
                    }
                    if (xmlNumber == _oldNumber)
                    {
                        item.SetAttribute("number", newNumber);
                    }
                }
                else
                {
                    //原位置开始改    xmlNumber > old > xmlNumber
                    if (xmlNumber > _oldNumber && xmlNumber <= _newNumber)
                    {
                        item.SetAttribute("number", (xmlNumber - 1).ToString());
                    }
                    if (xmlNumber == _oldNumber)
                    {
                        item.SetAttribute("number", newNumber);
                    }
                }
            }
            doc.Save(configPath);
        }

        public void ShowAddForm()
        {
            DragIn add = new DragIn(this);
            add.Show();
            //AppendIcon();
        }

        public void Test(string x, string y)
        {
            Console.WriteLine("Test ==> X:" + x + " Y:" + y);
        }

        #endregion

        #region C#调用JS

        private void SendIcon(string json)
        {
            object[] objects = new object[1];
            objects[0] = json;
            webBrowser1.Document.InvokeScript("ShowIcon", objects);
        }
        public void AppendIcon(string json)
        {
            object[] objects = new object[1];
            objects[0] = json;
            webBrowser1.Document.InvokeScript("AppendIcon", objects);
        }
        public void SetDrop(bool drop)
        {
            object[] objects = new object[1];
            objects[0] = drop;
            webBrowser1.Document.InvokeScript("SetDrop", objects);
        }
        #endregion

        #region C#
        //public delegate void CoreReadByte(string id, byte[] data);//委托
        //public event CoreReadByte ReadByte;//事件
        private void ShowDragIn()
        {
            DragIn form = new DragIn();
            form.Show();
        }


        // 加载图标数据到html显示
        public void Loading()
        {
            // 获取exe文件夹里的目录
            _exeFolder = new Models.FolderInfo()
            {
                icon = "",
                name = "exe",
                path = StartupPath + "\\NewFolder\\exe",
                files = new List<Models.FileInfo>(),
                folders = new List<Models.FolderInfo>()
            };
            GetFolder(StartupPath + "\\NewFolder\\exe\\", _exeFolder);
            // 获取图标文件
            icon = new List<Models.Icon>();
            GetIcon(StartupPath + "\\NewFolder\\icon\\", icon);
            ShowHtml(_exeFolder, icon);
        }


        private void ShowHtml(Models.FolderInfo folder, List<Models.Icon> icons)
        {
            // 展示实体类
            List<Models.ShowView> showView = new List<Models.ShowView>();
            try
            {
                // 加载文件信息
                foreach (var item in folder.files)
                {
                    string filePath = "";
                    if (PublicWay.IconType(item.path) == Models.MarkType.Image)
                    {
                        filePath = item.path;
                    }
                    else
                    {
                        filePath = (from icon in icons
                                    where (icon.mark == item.name && icon.markType == Models.MarkType.AppName)
                                    || (icon.mark == item.extension && icon.markType == Models.MarkType.ExtensionName)
                                    select icon.path).ToList()[0];//待完成
                    }

                    var number = (from config in desktopInfo
                                  where config.type.ToLower() == "file" && config.nowPath.GetName() == item.name
                                  select config.number)?.FirstOrDefault();


                    showView.Add(new Models.ShowView()
                    {
                        name = item.name,
                        path = filePath,
                        number = int.Parse(number),
                        fullName = item.path.Replace("\\", "/")
                    });
                }

                // 读取文件夹到展示实体
                foreach (var item in folder.folders)
                {
                    string folderType = ((item.files != null && item.files.Count() > 0)
                        || (item.folders != null && item.folders.Count() > 0))
                        ? "folder-full" : "folder-empty";

                    // 文件夹路径
                    var folderPath = (from icon in icons
                                      where icon.mark == folderType
                                      select icon.path).ToList();

                    // 排序序号
                    var number = (from config in desktopInfo
                                  where config.type.ToLower() == "folder" && config.nowPath.GetName() == item.name
                                  select config.number).ToList();

                    showView.Add(new Models.ShowView()
                    {
                        name = item.name,
                        path = folderPath[0],
                        number = int.Parse(number[0]),
                        fullName = item.path.Replace("\\", "/")
                    });
                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (showView.Count > 0)
                {
                    showView = (from s in showView orderby s.number select s).ToList();
                }
                string json = JsonConvert.SerializeObject(showView);
                SendIcon(json);
            }
        }

        /// <summary>
        /// 加载文件信息
        /// </summary>
        /// <param name="path"></param>
        /// <param name="folder"></param>
        private void GetFolder(string path, Models.FolderInfo folder)
        {
            Thread.Sleep(1);
            string[] filenames = Directory.GetFileSystemEntries(path);
            // 清除一次
            foreach (var item in filenames)
            {
                if (!desktopInfo.Where(t => t.nowPath.GetName().Equals(item.GetName())).Any() && !Directory.Exists(item))
                {
                    try
                    {
                        File.Delete(item);
                    }
                    catch { throw; }
                }
            }

            foreach (Models.DesktopInfo item in desktopInfo)
            {
                if (item.type.Equals("folder"))
                {
                    Models.FolderInfo folderInfo = new Models.FolderInfo();
                    folderInfo.name = item.originalPath.GetName();
                    folderInfo.files = new List<Models.FileInfo>();
                    folderInfo.folders = new List<Models.FolderInfo>();
                    // 将文件夹路径替换为绝对路径
                    folderInfo.path = item.originalPath;
                    folder.folders.Add(folderInfo);
                }
                else
                {
                    if (File.Exists(item.nowPath))
                    {
                        Models.FileInfo file = new Models.FileInfo();
                        file.name = item.nowPath.GetName();
                        file.path = item.nowPath;
                        file.extension = file.name.GetExtensionName();
                        folder.files.Add(file);
                    }
                }
            }

            #region obsolete

            //foreach (var item in filenames)
            //{
            //    if (Directory.Exists(item))
            //    {
            //        Models.FolderInfo folderInfo = new Models.FolderInfo();
            //        folderInfo.name = item.GetName();
            //        folderInfo.files = new List<Models.FileInfo>();
            //        folderInfo.folders = new List<Models.FolderInfo>();
            //        // 将文件夹路径替换为绝对路径
            //        var folderPath = (from info in desktopInfo
            //                          where info.type.Equals("folder", StringComparison.OrdinalIgnoreCase) && info.originalPath.GetName().Equals(item.GetName())
            //                          select info.originalPath)?.FirstOrDefault();

            //        folderInfo.path = folderPath ?? path;
            //        folder.folders.Add(folderInfo);
            //        // 不适用递归里面的文件
            //        //GetFolder(item, folderInfo);
            //    }
            //    else
            //    {
            //        Models.FileInfo file = new Models.FileInfo();
            //        file.name = item.GetName();
            //        file.path = item;
            //        file.extension = item.GetExtensionName();
            //        folder.files.Add(file);
            //    }
            //}
            #endregion
        }
        /// <summary>
        /// 加载图标信息
        /// </summary>
        /// <param name="path"></param>
        /// <param name="icon"></param>
        private void GetIcon(string path, List<Models.Icon> icons)
        {
            DirectoryInfo info = new DirectoryInfo(path);
            var files = info.GetFiles();
            foreach (var item in files)
            {
                icons.Add(new Models.Icon()
                {
                    path = "..\\NewFolder\\icon\\" + item.Name,
                    mark = item.Name.GetFileNameWithoutExtension(),
                    markType = (PublicWay.IconType(item.Name.GetFileNameWithoutExtension()) == Models.MarkType.AppName) ? Models.MarkType.AppName : Models.MarkType.ExtensionName
                });
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        private void OpenFile(string path)
        {
            try
            {
                if (!Directory.Exists(path) && !File.Exists(path))
                {
                    if (MessageBox.Show("文件或文件夹不存在，是否删除？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                        return;
                    else
                    {
                        ReadXml();
                        var xn = doc.SelectSingleNode("Desktop").SelectSingleNode("DesktopInfo"); ;
                        foreach (XmlNode node in xn.ChildNodes)
                        {
                            var np = node.Attributes["nowPath"].Value;
                            var op = node.Attributes["originalPath"].Value;
                            var name = path.GetName();

                            if (np.GetName().Equals(name, StringComparison.OrdinalIgnoreCase) || op.GetName().Equals(name, StringComparison.OrdinalIgnoreCase))
                            {
                                xn.RemoveChild(node);
                                doc.Save(configPath);
                                break;
                            }
                        }

                        Rerun();
                    }
                }
                var proc = new Process();
                if (path.GetExtensionName().ToLower() == "ico")
                {
                    //Windows图片查看器
                    proc.StartInfo.WorkingDirectory = path;
                    proc.StartInfo.FileName = "rundll32.exe";
                    proc.StartInfo.Arguments = @"C:\WINDOWS\system32\shimgvw.dll,ImageView_Fullscreen " + path;
                }
                else
                {
                    proc.StartInfo.FileName = Path.Combine(Environment.CurrentDirectory, path); //"输入完整的路径"
                }
                proc.Start();
            }
            catch (Exception e)
            {

            }
            /*
             * //Windows图片查看器
            string arg = string.Format(
                            "\"{0}\\Windows Photo Viewer\\PhotoViewer.dll\", ImageView_Fullscreen  {1} ",
                            Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
                            , path);
            var dllExe = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),
                       "rundll32.exe");
            System.Diagnostics.Process.Start(dllExe, arg);
            */

        }


        /// <summary>
        /// 完成拖动窗体后执行
        /// </summary>
        /// <returns>1：显示、0：隐藏</returns>
        public int Mouseup()
        {
            POINT ms = new POINT();
            GetCursorPos(out ms);
            double w = Screen.PrimaryScreen.Bounds.Width;
            //double h = Screen.PrimaryScreen.Bounds.Height;
            Point point = this.Location;
            if (ms.X < 3 || point.X <= 0)
            {
                //return OutAnimation(arrows: 4);
            }
            else if ((w - ms.X) < 3 || (point.X + this.Size.Width) >= w)
            {
                //return OutAnimation(arrows: 6);
            }
            else if (ms.Y < 3 || point.Y <= 0)
            {
                return OutAnimation(arrows: 8);
            }
            return 1;
        }

        /*
            Console.WriteLine("主显示器完整尺寸：");
            Console.WriteLine("宽：" + Screen.PrimaryScreen.Bounds.Width);
            Console.WriteLine("高：" + Screen.PrimaryScreen.Bounds.Height);

            Console.WriteLine("主显示器工作尺寸（排除任务栏、工具栏）：");
            Console.WriteLine("宽：" + Screen.PrimaryScreen.WorkingArea.Width);
            Console.WriteLine("高：" + Screen.PrimaryScreen.WorkingArea.Height);

            Console.WriteLine("当前显示器完整尺寸：");
            Console.WriteLine("宽：" + Screen.GetBounds(this).Width);
            Console.WriteLine("高：" + Screen.GetBounds(this).Height);

            Console.WriteLine("当前显示器工作尺寸（排除任务栏、工具栏）：");
            Console.WriteLine("宽：" + Screen.GetWorkingArea(this).Width);
            Console.WriteLine("高：" + Screen.GetWorkingArea(this).Height);
        */

        #region 鼠标位置 （相对显示器）

        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out POINT lpPoint);

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;
            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }
        #endregion


        /// <summary>
        /// 隐藏
        /// </summary>
        /// <param name="arrows">8:上、6右、xx、4左。</param>
        /// <returns>1：显示、0：隐藏</returns>
        private int OutAnimation(int arrows)
        {
            //new Task(() =>
            //{
            //}).Start();
            Point point = this.Location;
            Size size = this.Size;
            while (true)
            {
                if (arrows == 8)
                {
                    point.Y -= 25;
                    this.Location = point;
                    if (Math.Abs(point.Y) >= size.Height)
                    {
                        point.Y = 3 - size.Height;
                        this.Location = point;
                        break;
                    }
                }
                if (arrows == 4)
                {
                    point.X -= 30;
                    this.Location = point;
                    if (Math.Abs(point.X) >= size.Width)
                    {
                        point.X = 3 - size.Width;
                        this.Location = point;
                        break;
                    }
                }
                if (arrows == 6)
                {
                    point.X += 30;
                    this.Location = point;
                    if ((point.X - Screen.PrimaryScreen.Bounds.Width) >= size.Width)
                    {
                        point.X = Screen.PrimaryScreen.Bounds.Width - 2;
                        this.Location = point;
                        break;
                    }
                }
                Thread.Sleep(3);
            }
            return 0;
        }
        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="arrows">8:上、6右、xx、4左。</param>
        /// <returns>1：显示、0：隐藏</returns>
        private int InAnimation(int arrows)
        {
            Point point = this.Location;
            Size size = this.Size;
            while (true)
            {
                if (arrows == 8)
                {
                    point.Y += 25;
                    this.Location = point;
                    if (point.Y >= 0)
                    {
                        point.Y = 0;
                        this.Location = point;
                        break;
                    }
                }
                if (arrows == 4)
                {
                    //point.X -= 30;
                    //this.Location = point;
                    //Console.WriteLine(point.X);
                    //if (Math.Abs(point.X) >= size.Width)
                    //{
                    //    point.X = 3 - size.Width;
                    //    this.Location = point;
                    //    break;
                    //}
                }
                if (arrows == 6)
                {
                    //point.X += 30;
                    //this.Location = point;
                    //if ((point.X - Screen.PrimaryScreen.Bounds.Width) >= size.Width)
                    //{
                    //    point.X = Screen.PrimaryScreen.Bounds.Width - 2;
                    //    this.Location = point;
                    //    break;
                    //}
                }
                Thread.Sleep(3);
            }
            return 1;
        }

        #region 圆角
        /// <summary>
        /// 窗体圆角绘制
        /// </summary>
        public void SetWindowRegion()
        {
            System.Drawing.Drawing2D.GraphicsPath FormPath;
            FormPath = new System.Drawing.Drawing2D.GraphicsPath();
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
            FormPath = GetRoundedRectPath(rect, 10);
            this.Region = new Region(FormPath);
        }
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();

            // 左上角
            path.AddArc(arcRect, 180, 90);

            // 右上角
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);

            // 右下角
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);

            // 左下角
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();//闭合曲线
            return path;
        }

        #endregion

        #region 边框阴影

        private const int CS_DropSHADOW = 0x20000;
        private const int GCL_STYLE = (-26);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassLong(IntPtr hwnd, int nIndex);

        #endregion

        /// <summary>
        /// 读取嵌入资源
        /// </summary>
        /// <param name="resource">namespace.folder.file</param>
        /// <returns></returns>
        private Stream ReadResource(string resource)
        {
            Assembly assem = this.GetType().Assembly;
            return assem.GetManifestResourceStream(resource);
        }

        /// <summary>
        /// 展示窗体
        /// </summary>
        private void ShowHome()
        {
            if (this.Visible == false)
            {
                this.Show();
            }
            else
            {
                int y = this.Location.Y;
                if (y < 0)
                {
                    InAnimation(8);
                }
            }
            if (!this.TopMost)
            {
                this.Focus();
            }
        }

        #endregion

        #region 右下角窗体事件
        private void Icon_DoubleClick(object sender, EventArgs e)
        {
            ShowHome();
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowHome();
        }

        private void Home_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.notifyIcon1.Dispose();
        }
        #endregion
    }
}
